/*
 * Project Name spring-boot-tools
 * File Name CreateMysql
 * Package Name com.huxiaosu.toole.autocreate.database
 * Create Time 2024/7/9
 * Create by name：liujie
 */
package com.huxiaosu.tools.autocreate.database;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.huxiaosu.tools.autocreate.AutoCreateAware;
import com.huxiaosu.tools.autocreate.config.AutoCreateTableProperties;
import com.huxiaosu.tools.autocreate.utils.TableUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description
 *
 * @author liujie
 * @date 2024/7/9 15:33
 */
@Slf4j
public class CreateMysql implements EnvironmentAware, BeanFactoryAware, AutoCreateAware {

    private Environment environment;
    private BeanFactory beanFactory;
    @Override
    public void execute(){
        log.info("我要开始创建 MySQL 数据库了....");
        AutoCreateTableProperties autoCreateTableProperties = beanFactory.getBean(AutoCreateTableProperties.class);
        List<AutoCreateTableProperties.DataSourceConfig> datasourceConfig = autoCreateTableProperties.getDatasource();
        Map<String, Connection> allConnection = new HashMap<>(2);
        try {
            if (CollUtil.isEmpty(datasourceConfig) || datasourceConfig.isEmpty()) {
                String dbUrl = environment.getProperty("spring.datasource.url");
                String dbUsername = environment.getProperty("spring.datasource.username");
                String dbPassword = environment.getProperty("spring.datasource.password");
                if(StringUtils.isBlank(dbUrl) || StringUtils.isBlank(dbUsername)|| StringUtils.isBlank(dbPassword)){
                    throw new RuntimeException("没有配置数据库相关信息；spring.datasource is null...");
                }
                String dbName = TableUtil.getDbName(dbUrl);
                String tempDbUrl = dbUrl.replace(dbName, "mysql");
                allConnection.put(dbName, DriverManager.getConnection(tempDbUrl, dbUsername, dbPassword));
            }
            else {
                for (AutoCreateTableProperties.DataSourceConfig item : datasourceConfig) {
                    String[] split = item.getDatasource().split(",");
                    String dbName = TableUtil.getDbName(split[2]);
                    String tempDbUrl = split[2].replace(dbName, "mysql");
                    allConnection.put(dbName, DriverManager.getConnection(tempDbUrl, split[0], split[1]));
                }
            }
            for (Map.Entry<String, Connection> entry : allConnection.entrySet()) {
                String dbName = entry.getKey();
                Connection conn = entry.getValue();
                log.info("<start create databases {}>", dbName);
                String createDbSql = "create database if not exists " + dbName + " CHARACTER SET utf8;";
                conn.prepareStatement(createDbSql).execute();
                log.info("<create databases {} success>", dbName);
            }
        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }


    @Override
    public DbType getDbType() {
        return DbType.MYSQL;
    }


}